const jwt = require('jsonwebtoken')
const { code } = require('../static/secret')
const user = require('../model/user2')
const behavior = require('../model/behavior')
const fly = require('../model/partner')
const bcrypt = require('bcrypt')
const fs = require('fs-extra')

async function getId (ctx) {
  const token = await jwt.verify(ctx.header.authorization.split(' ')[1], code)
  return user.findOne({ username: token.username }, ['_id', 'role'])
}

function isAdmin (info) {
  let content = {}
  const { role } = info
  if (role !== 'admin') {
    content = {
      status: 401,
      message: '此身份请求不是管理员',
      data: {}
    }
  }
  return content
}

module.exports = {
  getPage: async function getPage (ctx) {
    const info = await getId(ctx)
    ctx.body = isAdmin(info)
    if (Object.keys(ctx.body).length !== 0) {
      return
    }
    if (ctx.query && 'limit' in ctx.query && ctx.query.limit >= 1) {
      const options = {
        select: ['_id', 'username', 'password', 'initialLevel', 'learnPurpose', 'planning', 'learnStyle', 'style'],
        limit: ctx.query.limit,
        page: 'page' in ctx.query ? ctx.query.page : 1
      }
      await user.paginate({ role: 'user' }, options, (err, doc) => {
        if (!err) {
          ctx.body = {
            status: 200,
            message: '查询成功',
            data: {
              total: doc.totalPages,
              page: doc.page,
              nextPage: doc.nextPage,
              list: doc.docs
            }
          }
        }
      })
    } else {
      ctx.body = {
        status: 403,
        message: '缺失每页具体数量',
        data: {}
      }
    }
  },
  changeInfo: async function changeInfo (ctx) {
    const info = await getId(ctx)
    ctx.body = await isAdmin(info)
    if (Object.keys(ctx.body).length !== 0) {
      return
    }
    if (ctx.request.body && 'id' in ctx.request.body && Object.keys(ctx.request.body).length > 1) {
      const member = await user.findById(ctx.request.body.id, 'username').lean()
      if ('username' in ctx.request.body && await user.findOne({ username: ctx.request.body.username })) {
        ctx.body = {
          status: 403,
          message: '用户名已存在，请重新设置',
          data: {}
        }
        return
      }
      const condition = {}
      for (const it in ctx.request.body) {
        if (it !== 'id') {
          condition[it] = ctx.request.body[it]
        }
        if (it === 'password') {
          await bcrypt.hash(ctx.request.body[it], 10)
        }
      }
      await user.findByIdAndUpdate(ctx.request.body.id, condition).then(async (res) => {
        if ('username' in ctx.request.body) {
          await behavior.updateOne({ username: member.username }, { username: ctx.request.body.username })
          await fly.cold.updateMany({ username: member.username }, { username: ctx.request.body.username })
          await fly.cold.updateMany({ partner: member.username }, { partner: ctx.request.body.username })
          await fly.partner.updateMany({ username: member.username }, { username: ctx.request.body.username })
          await fly.partner.updateMany({ partner: member.username }, { partner: ctx.request.body.username })
          if (fs.pathExistsSync('./upload/' + member.username)) {
            fs.renameSync('./upload/' + member.username, './upload/' + ctx.request.body.username)
          }
        }
        ctx.body = {
          status: 200,
          message: '信息修改成功',
          data: {}
        }
      }).catch(() => {
        ctx.body = {
          status: 403,
          message: '蠢货!用户id错误',
          data: {}
        }
      })
    } else {
      ctx.body = {
        status: 403,
        message: '请检查请求参数，参数错误或缺少必要条件，请求值必须携带用户id且不能只有id'
      }
    }
  },
  deleteUser: async function deleteUser (ctx) {
    const info = await getId(ctx)
    ctx.body = isAdmin(info)
    if (Object.keys(ctx.body).length !== 0) {
      return
    }
    const power = ctx.request.body
    if (power && 'id' in power) {
      const member = await user.findOne({ _id: power.id })
      if (member === null) {
        ctx.body = {
          status: 403,
          message: '蠢货!用户id错误',
          data: {}
        }
      } else {
        await user.findByIdAndDelete(power.id)
        await behavior.deleteOne({ username: member.username })
        await fly.cold.deleteMany({ $or: [{ username: member.username }, { partner: member.username }] })
        await fly.partner.deleteMany({ $or: [{ username: member.username }, { partner: member.username }] })
        fs.removeSync('./upload/' + member.username)
        ctx.body = {
          status: 200,
          message: '删除成功',
          data: {}
        }
      }
    } else {
      ctx.body = {
        status: 403,
        message: '缺少用户id',
        data: {}
      }
    }
  },
  select: async function select (ctx) {
    const info = await getId(ctx)
    ctx.body = isAdmin(info)
    if (Object.keys(ctx.body).length !== 0) {
      return
    }
    if (ctx.query && 'limit' in ctx.query) {
      const options = {
        select: ['_id', 'username', 'password', 'initialLevel', 'learnPurpose', 'planning', 'learnStyle', 'style'],
        limit: ctx.query.limit,
        page: 'page' in ctx.query ? ctx.query.page : 1
      }
      const condition = {}
      for (const it in ctx.query) {
        if (it !== 'limit' && it !== 'page') {
          condition[it] = ctx.query[it]
        }
      }
      condition.role = 'user'
      // await user.paginate(condition, options, (err, doc) => {
      //   if (!err) {
      //     ctx.body = {
      //       status: 200,
      //       message: '查询成功',
      //       data: {
      //         total: doc.totalPages,
      //         page: doc.page,
      //         nextPage: doc.nextPage,
      //         list: doc.docs
      //       }
      //     }
      //   } else {
      //     throw err
      //   }
      // })
      try {
        const doc = await user.paginate(condition, options)
        ctx.body = {
          status: 200,
          message: '查询成功',
          data: {
            total: doc.totalPages,
            page: doc.page,
            nextPage: doc.nextPage,
            list: doc.docs
          }
        }
      } catch (err) {
        ctx.body = {
          status: 404,
          message: err.message,
          data: {}
        }
      }
    } else {
      ctx.body = {
        status: 403,
        message: '页面容量呢？',
        data: {}
      }
    }
  }
}
